package io.yunho.yunho.interview.two.java8.stream;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

/**
 * @author: Jason
 * @date: 2021/5/8 21:18
 * @description:
 */
public class StreamTheory {
    public static void main(String[] args) {
        Random random = new Random();
        //随机产生数据
        Stream<Integer> integerStream = Stream.generate(() -> random.nextInt())
                //产生500个（无限流需要短路操作）
                .limit(500)
                //第一个无状态操作
                .peek(s -> print("peek: " + s))
                //第2个无状态操作
                .filter(s -> {
                    print("filter: " + s);
                    return s > 1000000;
                })
                //有状态操作
                .sorted((i1,i2)->{
                    print("排序： "+i1+" , "+i2);
                    return i1.compareTo(i2);
                })
                //无状态操作
                .peek(s->print("peek2: "+s))
                //并行操作
                .parallel()
                ;
        integerStream
                //终止操作 否则上边代码不会执行
                .count();
    }

    private static void print(String s) {
        System.out.println(Thread.currentThread().getName()+"_____"+s);
        try {
            TimeUnit.MILLISECONDS.sleep(5);} catch (InterruptedException e) {e.printStackTrace();}
    }
}
